package com.googlecode.lookie.swing.tree.render;

import java.awt.Component;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;

public class LabelProviderTreeCellRenderer
    implements TreeCellRenderer
{

    private LabelProvider provider;

    private TreeCellRenderer delegate;

    public LabelProviderTreeCellRenderer( LabelProvider provider )
    {
        this( provider, new DefaultTreeCellRenderer() );
    }

    public LabelProviderTreeCellRenderer( LabelProvider provider, TreeCellRenderer delegate )
    {
        super();
        this.provider = provider;
        this.delegate = delegate;
    }

    public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded,
                                                   boolean leaf, int row, boolean hasFocus )
    {

        Component component = delegate.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row,
                                                                     hasFocus );

        if ( component instanceof JLabel )
        {
            JLabel label = (JLabel) component;
            label.setText( convertValueToText( value ) );
            Icon icon = convertValueToIcon( value );
            if ( icon != null )
            {
                label.setIcon( icon );
            }
        }

        return component;
    }

    private Icon convertValueToIcon( Object value )
    {
        Icon icon = null;
        if ( value instanceof TreeNode )
        {
            icon = provider.getIcon( (TreeNode) value );
        }
        return icon;
    }

    private String convertValueToText( Object value )
    {
        String text = null;
        if ( value instanceof TreeNode )
        {
            text = provider.getText( (TreeNode) value );
        }
        if ( text == null )
        {
            text = value.toString();
        }
        return text == null ? "" : text;
    }

}
